$(function() {
    //选择一个客户
    $("#companyName").dblclick(function() {
        $.baseMultiCustomerApi({
            getBaseValue: function(customers) {
                $("#customerinfoid").val((_.pluck(customers, "id")).join(","));
                $("#companyCode").val((_.pluck(customers, "companycode")).join(","));
                $("#companyName").val((_.pluck(customers, "customername")).join(","));
            },
        });
    });
    //首次打开页面时获取默认数据
    energyAnalysis($("#companyCode").val(), $("#startDate").val(), $("#endDate").val());

    //执行查询操作
    $("#searchEnergy").click(function() {
        energyAnalysis($("#companyCode").val(), $("#startDate").val(), $("#endDate").val());
    });

    function energyAnalysis(companyCode, startDate, endDate) {
        var param = {
            "companyCode": companyCode,
            "startDate": startDate,
            "endDate": endDate
        };

        $.ajax({
            contentType: "application/json",
            url: "getAllNightByDate.shtml",
            data: param,
            async: false,
            dataType: "json",
            success: function(data) {
                var dates = _.uniq(_.sortBy(_.pluck(data, 'sysdate')));
                var group = _.groupBy(data, 'customername');
                var keys = _.keys(group);
                var series = [];
                for (var i = 0; i < keys.length; i++) {
                    var serie = {};
                    serie.name = keys[i];
                    var property = _.property(keys[i])(group);
                    //考虑到有的公司某些月份时数据为空的情况，因此需要补充数据
                    if (property.length < dates.length) {
                        for (var j = 0; j < dates.length; j++) {
                            if (!_.contains(_.pluck(property, 'sysdate'), dates[j])) {
                                var obj = {};
                                obj.sysdate = dates[j];
                                obj.count = 0;
                                property[property.length] = obj;
                            }
                        }
                    }
                    serie.data = _.pluck(_.sortBy(property, 'sysdate'), 'count');
                    series[i] = serie;
                }
                bar('container', '通宵天数分析表', dates[0] + '~' + dates[dates.length-1], dates, '通宵天数（天）', series,'人');
            }
        });
    }


});
